﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AdverseEventReportSystem.Model;
using AdverseEventReportSystem.Service;
using System.Data;
using AdverseEventReportSystem.Utils;
using AdverseEventReportSystem.Core;
using AdverseEventReportSystem.BLL;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Text;
using AdverseEventReportSystem.BLL.ServiceReference1;
using System.Data.SqlClient;

namespace AdverseEventReportSystem.Web.Areas.AdverseEvent
{
    public class EditAdverseEventController : BaseController
    {
        // GET: /AdverseEvent/EditAdverseEvent/
        public ActionResult Index(int id = 0, int pageType = 0, string detailsViewBtns = "", int status = 0)
        {
            ViewBag.EventID = id;
            ViewBag.PageType = pageType;
            ViewBag.PersonnelId = loginUser.Personnel_id;
            ViewBag.UserName = loginUser.Name;
            ViewBag.CurrDepCode = loginUser.CurrDepCode;
            ViewBag.DetailsViewBtns = detailsViewBtns;
            ViewBag.Status = status;
            return View();
        }

        /// <summary>
        /// 获取不良事件详情
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAdverseEvent(int id)
        {
            Model.AdverseEvent adverseEvent = AdverseEventService.GetQuerySingleByID(id);
            return JsonDate(adverseEvent);
        }

        /// <summary>
        /// 获取事件类型
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAdverseEventTypeList()
        {
            DataTable dt = AdverseEventTypeService.GetAdverseEventTypeTable();
            return JsonDate(dt);
        }

        /// <summary>
        /// 根据事件类型获取发生方式
        /// </summary>
        /// <param name="typeID"></param>
        /// <param name="eventID"></param>
        /// <returns></returns>
        public ActionResult GetAdverseEventModeList(int typeID, int eventID)
        {
            DataTable dt = new DataTable();
            if (eventID == 0)
            {
                dt = AdverseEventModeService.GetAdverseEventModeTable(typeID);
            }
            else
            {
                dt = AdverseEventModeRecordService.GetAdverseEventModeRecordTable(eventID, typeID);
            }
            return JsonDate(dt);
        }

        /// <summary>
        /// 根据事件类型获取根因
        /// </summary>
        /// <param name="typeID"></param>
        /// <param name="eventID"></param>
        /// <returns></returns>
        public ActionResult GetAdverseEventReasonList(int typeID, int eventID)
        {
            DataTable dt = new DataTable();
            if (eventID == 0)
            {
                dt = AdverseEventReasonService.GetAdverseEventReasonTable(typeID);
            }
            else
            {
                dt = AdverseEventReasonRecordService.GetAdverseEventReasonRecordTable(eventID, typeID);
            }
            return JsonDate(dt);
        }

        /// <summary>
        /// 根据事件ID获取压疮发生部位
        /// </summary>
        /// <param name="eventID"></param>
        /// <returns></returns>
        public ActionResult GetAdverseEventYaChuangFsbwList(int eventID)
        {
            DataTable dt = AdverseEventYaChuangFsbwService.GetAdverseEventYaChuangFsbwTable(eventID);
            return JsonDate(dt);
        }

        /// <summary>
        /// 获取患者
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPatientList(string departmentCode, int isDischargedPatients = 0)
        {
            DataTable dt = new DataTable();
            FunctionAndPermissionsSoapClient service = new FunctionAndPermissionsSoapClient();
            if (isDischargedPatients == 0)
            {
                ResultHelperOfDataTable result = service.getDepartmentCodePatients(departmentCode);
                if (result.S)
                {
                    dt = result.D;
                }
            }
            else
            {
                DataTable cyDt = null;
                ResultHelperOfDataTable result = service.GetPatientInfoByType(DateTime.Now.AddDays(-7), DateTime.Now, 1, "", departmentCode, false);
                if (result.S)
                {
                    cyDt = dt = result.D;
                }
                DataTable zcDt = null;
                result = service.GetPatientInfoByType(DateTime.Now.AddDays(-7), DateTime.Now, 3, "", departmentCode, false);
                if (result.S)
                {
                    zcDt = dt = result.D;
                }
                if (cyDt != null && zcDt != null)
                {
                    cyDt.Merge(zcDt);
                    dt = cyDt;
                }
            }
            if (dt.Rows.Count > 0)
            {
                dt.DefaultView.Sort = "BED_NO";
                dt = dt.DefaultView.ToTable();
            }
            return JsonDate(dt);
        }

        /// <summary>
        /// 根据事件ID获取当事人
        /// </summary>
        /// <param name="eventID"></param>
        /// <returns></returns>
        public ActionResult GetAdverseEventNurse(int eventID)
        {
            DataTable dt = AdverseEventNurseService.GetAdverseEventNuserTable(eventID);
            return JsonDate(dt);
        }

        /// <summary>
        /// 添加/编辑不良事件
        /// </summary>
        /// <param name="adverseEventInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(AdverseEventInfo adverseEventInfo)
        {
            OperateResult resultInfo = AdverseEventManager.Save(adverseEventInfo);
            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 鱼骨图
        /// </summary>
        /// <returns></returns>
        public ActionResult PaintYG(int eventID)
        {
            ViewBag.EventID = eventID;
            return View();
        }

        /// <summary>
        /// 显示/打印鱼骨图
        /// </summary>
        /// <param name="eventID"></param>
        /// <param name="reportType"></param>
        /// <returns></returns>
        [LoginAttribute(IsNeed = false)]
        public ActionResult ShowPaintYG(int eventID, int reportType = 0)
        {
            Model.AdverseEvent adverseEvent = AdverseEventService.GetQuerySingleByID(eventID);
            DataTable dt = AdverseEventReasonRecordService.GetAdverseEventReasonRecordTable(eventID, adverseEvent.EventTypeID);
            var d = (from r in dt.AsEnumerable() where r.Field<object>("IsChecked") != null select r);
            if (d.Count() > 0)
            {
                dt = d.CopyToDataTable<DataRow>();
            }
            else
            {
                dt.Rows.Clear();
            }
            foreach (DataRow item in dt.Rows)
            {
                string[] reason = item["Reason"].ToString().Split('#');
                if (reason.Contains("其他"))
                {
                    if (item["OtherReason"].ToString().Trim() != "")
                        reason[Array.IndexOf(reason, "其他")] = item["OtherReason"].ToString();
                    item["Reason"] = string.Join("#", reason);
                }
                if (reason.Contains("其它"))
                {
                    if (item["OtherReason"].ToString().Trim() != "")
                        reason[Array.IndexOf(reason, "其它")] = item["OtherReason"].ToString();
                    item["Reason"] = string.Join("#", reason);
                }
            }
            WebPaintPic bll = new WebPaintPic();
            Bitmap img = new Bitmap(400, 200);//创建Bitmap对象
            MemoryStream stream = bll.drawYG(adverseEvent.EventTypeName, dt);
            img.Save(stream, ImageFormat.Jpeg);//保存绘制的图片
            img.Dispose();
            Response.Clear();
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");

            if (reportType == 0)
            {
                return File(stream.ToArray(), "image/jpeg");
            }
            else
            {
                string stImageByte = Convert.ToBase64String(stream.ToArray());
                var result = new { YG = new List<YG> { new YG { FishboneDiagram = stImageByte } } };
                return JsonDate(result);
            }
        }

        /// <summary>
        /// 打印报表
        /// </summary>
        /// <returns></returns>
        public ActionResult Report(int eventID, int flag_Yc = 0)
        {
            ViewBag.EventID = eventID;
            ViewBag.Flag_Yc = flag_Yc;
            return View();
        }

        /// <summary>
        /// 获取报表数据
        /// </summary>
        /// <param name="eventID"></param>
        /// <returns></returns>
        [LoginAttribute(IsNeed = false)]
        public ActionResult GetReportData(int eventID)
        {
            DataTable dt = AdverseEventService.GetAdverseEventTable(eventID);
            if (eventID == 0)
            {
                return JsonDate(new { EventInfo = dt, ModeList = new { }, EventInfo1 = dt });
            }
            DataRow eventDr = dt.Rows[0];
            if (DataConvert.StrToInt(eventDr["EventGrade"]) > 0)
            {
                eventDr["EventGrade"] = DataConvert.GetLoumaNumber(DataConvert.StrToInt(eventDr["EventGrade"])) + "级";
                if (eventDr["EventGradeSubLevel"].ToString() != "")
                {
                    eventDr["EventGrade"] += "/" + eventDr["EventGradeSubLevel"].ToString() + "级";
                }
            }
            else
            {
                eventDr["EventGrade"] = "其他";
            }
            switch (eventDr["PatientNursingGrade"].ToString())
            {
                case "c001":
                    eventDr["PatientNursingGrade"] = "全部";
                    break;
                case "c002":
                    eventDr["PatientNursingGrade"] = "新入";
                    break;
                case "c003":
                    eventDr["PatientNursingGrade"] = "一般";
                    break;
                case "c004":
                    eventDr["PatientNursingGrade"] = "病危";
                    break;
                case "c005":
                    eventDr["PatientNursingGrade"] = "病重";
                    break;
                case "c006":
                    eventDr["PatientNursingGrade"] = "特级护理";
                    break;
                case "c007":
                    eventDr["PatientNursingGrade"] = "Ⅰ级护理";
                    break;
                case "c008":
                    eventDr["PatientNursingGrade"] = "Ⅱ级护理";
                    break;
                case "c009":
                    eventDr["PatientNursingGrade"] = "重症监护";
                    break;
                case "c0010":
                    eventDr["PatientNursingGrade"] = "今日手术";
                    break;
                case "c0011":
                    eventDr["PatientNursingGrade"] = "术后1天";
                    break;
                case "c0012":
                    eventDr["PatientNursingGrade"] = "术后2天";
                    break;
                case "c0013":
                    eventDr["PatientNursingGrade"] = "术后3天";
                    break;
                case "c0014":
                    eventDr["PatientNursingGrade"] = "明日出院";
                    break;
                default:
                    eventDr["PatientNursingGrade"] = "";
                    break;
            }
            if (DataConvert.StrToInt(eventDr["PatientIsEscort"]) == 0)
            {
                eventDr["PatientEscortValue"] = "无";
            }
            else
            {
                eventDr["PatientEscortValue"] = "有";
            }

            AdverseEventType type = AdverseEventTypeService.GetQuerySingleByID(DataConvert.StrToInt(eventDr["EventTypeID"]));
            DataTable modeDt = AdverseEventModeRecordService.GetAdverseEventModeRecordTable(eventID, DataConvert.StrToInt(eventDr["EventTypeID"]));
            modeDt.Columns.Add("Num", typeof(int));
            modeDt.Columns.Add("RowNum", typeof(int));
            modeDt.Columns.Add("TypeName", typeof(string));
            for (int i = 1; i <= modeDt.Rows.Count; i++)
            {
                DataRow dr = modeDt.Rows[i - 1];
                dr["Num"] = Math.Ceiling(i / 2.0);
                dr["RowNum"] = (i + 1) % 2;
                dr["TypeName"] = type.Name;

                if (dr["Value"].ToString() == "") continue;

                if (DataConvert.StrToInt(dr["InputType"]) < 2)
                {
                    string[] options = dr["Options"].ToString().Split('#');
                    string[] values = dr["Value"].ToString().Split('#');
                    string value = "";

                    if (type.Name == "压力性损伤")
                    {
                        if (dr["ModeName"].ToString() == "感觉" || dr["ModeName"].ToString() == "潮湿" || dr["ModeName"].ToString() == "活动能力" || dr["ModeName"].ToString() == "移动能力" || dr["ModeName"].ToString() == "营养" || dr["ModeName"].ToString() == "摩擦力")
                        {
                            for (int j = 0; j < options.Length; j++)
                            {
                                options[j] = options[j].Split('☆')[0];
                            }
                        }
                        if (dr["ModeName"].ToString() == "发生部位")
                        {
                            dr["Value"] = "";
                            DataTable fsbwDt = AdverseEventYaChuangFsbwService.GetAdverseEventYaChuangFsbwTable(eventID);
                            foreach (DataRow item in fsbwDt.Rows)
                            {
                                value += item["Name"].ToString() + item["Position"].ToString() + "：";
                                if (!(string.IsNullOrWhiteSpace(item["StartRange"].ToString()) || string.IsNullOrWhiteSpace(item["EndRange"].ToString())))
                                {
                                    value += item["StartRange"].ToString() + "cm×" + item["EndRange"].ToString() + "cm，";
                                }
                                value += item["YcLevel"].ToString();
                                if (!string.IsNullOrWhiteSpace(item["Remarks"].ToString())) value += "，" + item["Remarks"].ToString();
                                value += "，" + item["Seepage"].ToString() + "渗液";
                                value += "，" + item["PeculiarSmell"].ToString() + "异味";
                                value += "\n";
                                dr["Value"] += item["Name"].ToString() + item["Position"].ToString() + "，"; ;
                            }
                            eventDr["EventCourse"] = (eventDr["EventCourse"].ToString() + "\n" + value).TrimEnd("\n".ToCharArray());
                            dr["Value"] = dr["Value"].ToString().TrimEnd("，".ToCharArray());
                            continue;
                        }
                    }

                    for (int ii = 0; ii < options.Length; ii++)
                    {
                        string[] tempOptions = options[ii].ToString().Split(new string[] { "$0%" }, StringSplitOptions.None);
                        string[] tempValues = values[ii].ToString().Split(new string[] { "$0%" }, StringSplitOptions.None);

                        if (DataConvert.StrToInt(tempValues[0]) > 0)
                        {
                            value += tempOptions[0] + " ";

                            if (tempOptions.Length > 1)
                            {
                                if (options[ii].Contains("$0%0*") || options[ii].Contains("$0%1*"))
                                {
                                    string[] tempOptions1 = null;
                                    string[] tempValues1 = null;
                                    if (options[ii].Contains("$0%0*"))
                                    {
                                        tempOptions1 = options[ii].ToString().Split(new string[] { "$0%0*" }, StringSplitOptions.None);
                                        tempValues1 = values[ii].ToString().Split(new string[] { "$0%0*" }, StringSplitOptions.None);
                                    }
                                    else if (options[ii].Contains("$0%1*"))
                                    {
                                        tempOptions1 = options[ii].ToString().Split(new string[] { "$0%1*" }, StringSplitOptions.None);
                                        tempValues1 = values[ii].ToString().Split(new string[] { "$0%1*" }, StringSplitOptions.None);
                                    }

                                    string[] opt = tempOptions1[1].Split('@');
                                    string[] val = tempValues1[1].Split('@');
                                    for (int iii = 0; iii < opt.Length; iii++)
                                    {
                                        if (DataConvert.StrToInt(val[iii]) > 0)
                                        {
                                            value += opt[iii] + "  ";
                                        }
                                    }
                                }
                                else
                                {
                                    string[] tempOptions1 = null;
                                    string[] tempValues1 = null;
                                    if (options[ii].Contains("$0%2*"))
                                    {
                                        tempOptions1 = options[ii].ToString().Split(new string[] { "$0%2*" }, StringSplitOptions.None);
                                        tempValues1 = values[ii].ToString().Split(new string[] { "$0%2*" }, StringSplitOptions.None);
                                    }
                                    else if (options[ii].Contains("$0%3*"))
                                    {
                                        tempOptions1 = options[ii].ToString().Split(new string[] { "$0%3*" }, StringSplitOptions.None);
                                        tempValues1 = values[ii].ToString().Split(new string[] { "$0%3*" }, StringSplitOptions.None);
                                    }
                                    value += tempValues1[1].Replace("$0%2*", "").Replace("$0%3*", "");
                                }
                            }
                            if (value.IndexOf('（') > -1)
                                dr["Value"] = value.Substring(0, value.IndexOf('（'));
                            else
                                dr["Value"] = value;
                        }
                    }
                }
            }
            if (modeDt.Rows.Count == 1)
            {
                DataRow dr = modeDt.NewRow();
                dr["TypeID"] = modeDt.Rows[0]["TypeID"];
                dr["ModeID"] = 0;
                dr["ModeName"] = "";
                dr["InputType"] = 0;
                dr["Options"] = "";
                dr["Num"] = 1;
                dr["RowNum"] = 1;
                dr["TypeName"] = "";
                modeDt.Rows.Add(dr);
            }
            var result = new { EventInfo = dt, ModeList = modeDt, EventInfo1 = dt };
            return JsonDate(result);
        }

        /// <summary>
        /// 打印报表
        /// </summary>
        /// <returns></returns>
        public ActionResult EventPrint(int eventID, int flag_Yc = 0)
        {
            ViewBag.EventID = eventID;
            ViewBag.Flag_Yc = flag_Yc;
            return View();
        }

        /// <summary>
        /// 打印鱼骨图
        /// </summary>
        /// <returns></returns>
        public ActionResult YGPrint(int eventID)
        {
            ViewBag.EventID = eventID;
            return View();
        }
    }
}

public class YG
{
    public string FishboneDiagram { get; set; }
}